<template>
  <div class="user-group-list-container">
    <el-aside width="230px">
      <div class="aside-header">
        <div class="aside-header-title">
          <div>
            <h3>短链分组</h3>
            <span class="group-num">共{{ groupData.groupTotal }}组</span>
          </div>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="openGroupDialog('创建分组')"></el-button>
        </div>
      </div>
      <el-menu :default-active="$route.params.id" @select="selectGroup">
        <el-menu-item index="0">
          <div class="group-title">
            <span class="iconfont icon-tuozhuai"></span>
            默认分组
          </div>
          <div class="group-btn">
            <img src="/img/table-operate-images/curve_icon.png" alt="curve_icon" @click.stop="openStatisticsDialog('默认分组',0)">
          </div>
          <div class="group-quantity">
            {{ groupData.groupList.defult }}
          </div>
        </el-menu-item>
        <VueDraggableNext v-model="groupData.groupList.short" @change="draggable" animation="300">
          <transition-group>
            <el-menu-item v-for="item in groupData.groupList.short" :key="item.id" :index="(item.id).toString()">
              <div class="group-title">
                <span class="iconfont icon-tuozhuai"></span>
                {{ item.name }}
              </div>
              <div class="group-btn">
                <img src="/img/table-operate-images/curve_icon.png" alt="curve_icon" @click.stop="openStatisticsDialog(item.name,item.id)">
                <img class="more-icon-img" :src="imgRootSrc+'more_icon.png'" alt="more_icon">
                <el-dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click.stop="openGroupDialog('编辑分组',item)">编辑</el-dropdown-item>
                    <el-dropdown-item @click.stop="delGroup([item.id])">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div class="group-quantity">{{ item.short_num }}</div>
            </el-menu-item>
          </transition-group>
        </VueDraggableNext>
      </el-menu>
    </el-aside>
    <el-main>
      <router-view @update:refreshGroupList="getGroup" :groupTitle="groupData.groupTitle"></router-view>
    </el-main>
  </div>
  <!-- 创建或修改分组对话框start -->
  <el-dialog :title="groupData.groupDialogTitle" v-model="groupData.showGroupDialog" @closed="closeDialog('groupFormRef')" width="500px" @opened="$refs.groupNameInputRef.focus()">
    <el-form :model="groupData.groupForm" ref="groupFormRef" label-position="top" @submit.native.prevent>
      <el-form-item label="分组名称" prop="name" :rules="[{ required:true,message:'请输入分组名' }]">
        <el-input ref="groupNameInputRef" v-model.trim="groupData.groupForm.name" placeholder="请输入分组名" clearable @keyup.enter="submitGroupName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="default" size="mini" @click="groupData.showGroupDialog = false">取消</el-button>
      <el-button type="primary" size="mini" @click="submitGroupName" :loading="groupData.changing">确定</el-button>
    </template>
  </el-dialog>
  <DataStatistics ref="dataStatisticsRef" v-if="statisticsData.showStatisticsDialog" :statisticsData="statisticsData"></DataStatistics>
</template>

<script setup>
import DataStatistics from '@/components/usersComponents/statistics/dataStatistics'
import { VueDraggableNext } from 'vue-draggable-next'
import { reactive, getCurrentInstance } from 'vue'
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router'
const { proxy } = getCurrentInstance()
import { getShort, addShort, editShort, delShort, groupSort } from '@/axios/userRequest'
const imgRootSrc = '/img/my-short-chain-images/short-chain-management-images/'
const router = useRouter()
const route = useRoute()
// 分组数据
const groupData = reactive({
  groupList:[],// 分组列表
  showGroupDialog:false,// 分组对话框显示
  groupDialogTitle:'',// 分组对话框标题
  changing:false,// 创建或修改中
  groupForm:{
    name: '',// 分组名
    type: 2,
    id: '',
  },
  groupTitle: '',
  groupTotal: 0,
})
// 获取分组
const getGroup = async ()=>{
  const res = await getShort({ type:2 })
  if(res.code === 0){
    groupData.groupList = res.data
    groupData.groupTotal = res.data.short.length+1
    let haveId = [0]
    res.data.short.forEach(item => {
      haveId.push(item.id)
      route.params.id != 0 ? route.params.id == item.id ? groupData.groupTitle = item.name : '' : groupData.groupTitle = '默认分组'
    })
    !haveId.includes(Number(route.params.id)) ? await router.push('/user-center/short-link-manage/0') : ''
  }else{
    proxy.$message.error(res.msg)
  }
}
getGroup()

onBeforeRouteUpdate(to=>{
  if(to.params.id != 0){
    groupData.groupList.short.find(item=>{
      to.params.id == item.id ? groupData.groupTitle = item.name : ''
    })
  }else{
    groupData.groupTitle = '默认分组'
  }
})
// 打开添加或修改分组对话框
const openGroupDialog = (title,item = '') =>{
  groupData.showGroupDialog = true
  groupData.groupDialogTitle = title
  groupData.groupForm.id = groupData.groupForm.name = ''
  if(title === '编辑分组'){
    groupData.groupForm.id = item.id
    groupData.groupForm.name = item.name
  }
}
// 创建或修改分组方法
const submitGroupName = ()=>{
  proxy.$refs.groupFormRef.validate(async validate=>{
    if(validate){
      groupData.changing = true
      let res = groupData.groupDialogTitle === '创建分组' ? await addShort(groupData.groupForm) : await editShort(groupData.groupForm)
      if(res.code === 0){
        console.log(res)
        groupData.showGroupDialog = false
        proxy.$message.success(res.msg)
        await getGroup()
        groupData.groupDialogTitle === '创建分组' ? await router.push(`/user-center/short-link-manage/${res.data.id}`) : ''
      }else{
        proxy.$message.error(res.msg)
      }
      groupData.changing = false
    }
  })
}
// 删除分组
const delGroup = id=>{
  proxy.$confirm('删除分组会将该分组移动回收站，如果分组内存在短链依然可以跳转和统计数据，是否确定删除？','删除分组',{
    closeOnClickModal:false,
    customClass:'commonMessageBox',
    type: 'warning',
  }).then(async ()=>{
    const res = await delShort({ id, type:2 })
    if(res.code === 0){
      proxy.$message.success(res.msg)
      await getGroup()
    }else{
      proxy.$message.error(res.msg)
    }
  }).catch(err=>{})
}
// 拖拽
const draggable = async ()=>{
  let ids = groupData.groupList.short.map(item=>item.id)
  const res = await groupSort(ids)
  res.code === 0 ? await getGroup() : proxy.$message.error(res.msg)
}
// 选择分组
const selectGroup = index=>{
  router.push(`/user-center/short-link-manage/${index}`)
}
// 数据统计数据
const statisticsData = reactive({
  showStatisticsDialog:false,
  type:1,
  shortData:{// 短链数据
    name:''
  },
  formData:{
    type: 2,// 短链查询
    f_id: null,// 短链id
  }
})
// 打开数据统计
const openStatisticsDialog = (name,id)=>{
  statisticsData.showStatisticsDialog = true
  statisticsData.shortData.name = name
  statisticsData.formData.f_id = id
}
// 关闭对话框
const closeDialog = refName =>{
  proxy.$refs[refName].resetFields()
}
</script>

<style lang="less" scoped>
</style>
